import logging

from aiogram import Bot
from fluentogram import TranslatorRunner
from sqlalchemy.ext.asyncio import AsyncSession

from src.application.order.enums import AuthorizationType, OrderType
from src.infrastructure.db.services.allowed_ips import (
    add_ip_to_order,
    get_allowed_ip_by_order,
    get_ip,
    remove_ip_from_order,
)
from src.infrastructure.db.services.orders.common import get_order
from src.infrastructure.db.services.proxy import update_authorization_type
from src.infrastructure.ssh.async_ssh_connector import change_authorization_type
from src.infrastructure.utils.helpers import get_server_proxies
from src.presentation.tg_bot.services.tg_helpers import broadcast
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def change_authorization_type_job(
    ctx,
    locale: TranslatorRunner,
    user_id: int,
    order_id: int,
    allowed_ip_id: int,
    authorization_type: AuthorizationType,
) -> None:
    """Change proxy authorization type (by link or by password)"""

    bot: Bot = ctx["bot"]
    session: AsyncSession = ctx["session"]

    try:
        order = await get_order(session, order_id, joined=True)

        old_ip = await get_allowed_ip_by_order(session, user_id, order_id)

        if old_ip:
            if authorization_type == AuthorizationType.by_password:
                await remove_ip_from_order(session, order, old_ip)

        ip_address = None
        if allowed_ip_id:
            ip_address = await get_ip(session, allowed_ip_id)
            if old_ip:
                # Меняем старый разрешенный ip на новый
                # Каждый юзер может добавить только 1 ip к заказу
                await remove_ip_from_order(session, order, old_ip)
                await add_ip_to_order(session, order, ip_address)
            else:
                await add_ip_to_order(session, order, ip_address)
                # Добавляем разрешенный ip к заказу

        server_proxies = await get_server_proxies(session, order.proxies)

        for server, proxies in server_proxies.items():
            await change_authorization_type(server, proxies, authorization_type, old_ip, ip_address)
            await update_authorization_type(session, proxies, authorization_type)

        if order.type == OrderType.subscription:
            msg = locale.get("subscription-authorization-change-success")
        else:
            msg = locale.get("authorization-change-success", order_id=str(order.id))
        await broadcast(
            bot,
            [user_id],
            msg,
        )

        logger.info(f"Изменена авторизация заказа №{order.id}")

    except Exception as e:
        if order.type == OrderType.subscription:
            msg = locale.get("subscription-change-authorization-error")
        else:
            msg = locale.get("change-authorization-error", order_id=str(order.id))
        await broadcast(bot, [user_id], msg)
